package UHF18;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description: 读卡程序
 * @author: hubin
 * @email: nightt0428@gmail.com
 * @date: 2022/8/26 10:56
 */
public class ReaderCard {

    /**
     * 主程序
     *
     * @param args
     * @throws IOException
     */
    public static void main(String args[]) throws IOException {
        //设置端口
        int port = 8094;

        //定义一个ServerSocket监听在端口8089上
        ServerSocket server = new ServerSocket(port);

        while (true) {
            //server尝试接收其他Socket的连接请求，server的accept方法是阻塞式的
            Socket socket = server.accept();
            //每接收到一个Socket就建立一个新的线程来处理它
            new Thread(new Task(socket)).start();
        }

    }

    /**
     * 用来处理Socket请求的
     */
    static class Task implements Runnable {

        private Socket socket;

        public Task(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {
                handleSocket();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /**
         * 跟客户端Socket进行通信
         *
         * @throws Exception
         */
        private void handleSocket() throws Exception {
            //使用字节流，防止不能换行输出
            InputStream is = socket.getInputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                String str = new String(buffer, 0, len);
                System.out.println(str);
                //转成16进制输出
                convertStringToHex(str);
            }
            is.close();
            socket.close();
        }
    }

    /**
     * 将字符串转为16进制
     *
     * @param str
     */
    private static void convertStringToHex(String str) {
        StringBuilder stringBuilder = new StringBuilder();

        char[] charArray = str.toCharArray();

        for (char c : charArray) {
            String charToHex = Integer.toHexString(c);
            stringBuilder.append(charToHex);
        }
        System.out.println(stringBuilder);
    }
}